<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    <input type="button" id="btn1" value="按钮1">
    <input type="button" id="btn2" value="按钮2">
</body>
<script>

    const obtn1 = document.getElementById("btn1")
    const obtn2 = document.getElementById("btn2")

    obtn1.onclick = function(){
        const url = "http://localhost:3000/api";
        ajaxPost(url, {
            type:"login"
        },function(res){
            console.log(res);
        })
    }

    obtn2.onclick = function(){
        const url = "http://127.0.0.1:3000/api";
        ajaxPost(url, {
            type:"register"
        },function(res){
            console.log(res);
        })
    }




    function ajaxPost(url, data, success){
        if(typeof data !== "object"){
            success = data;
            data = {};
        }
        let str = "";
        for(let i in data){
            str += `${i}=${data[i]}&`
        }
        const xhr = new XMLHttpRequest();
        xhr.open("post", url);
        xhr.onload = function(){
            if(xhr.status === 200){
                success(xhr.responseText);
            }
        }
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(str.slice(0, -1));
    }
</script>
</html>